<template>
  <el-form-item
    :rules="rule"
    class="xmf-select"
    :label="label"
    :prop="prop"
    clearable
  >
    <el-select
      v-model="title"
      value-key="value"
      :multiple="isMultiple"
      :placeholder="placeholder"
      class="header-search-select"
      clearable
      :disabled="disabled"
      @change="change"
      :style="{ width: $slots.default ? '85%' : '100%' }"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      ></el-option>
    </el-select>
    <span :style="{ width: $slots.default ? '15%' : '0%' }">
      <slot />
    </span>
  </el-form-item>
</template>
<script>
  import { computed } from '@vue/reactivity'
  import { isString, isArray } from '@/utils/validate.js'
  export default {
    name: 'XmFSelect',
    components: ['change'],
    props: {
      modelValue: [String, Number, Boolean],
      options: {
        type: Array,
        default() {
          return []
        },
      },
      disabled: {
        type: Boolean,
        default() {
          return false
        },
      },
      rows: {
        type: Number,
        default() {
          return 4
        },
      },
      label: String,
      foots: String,
      prop: String,
      quick: Boolean,
      isMultiple: {
        type: Boolean,
        default() {
          return false
        },
      },
    },
    setup(props, context) {
      let title = computed({
        get() {
          if (
            props.isMultiple &&
            isString(props.modelValue) &&
            props.modelValue
          ) {
            return props.modelValue.split(',')
          }

          if (props.isMultiple) return []
          return props.modelValue
        },
        set(val) {
          if (props.isMultiple && isArray(val)) {
            const tmp = val.length > 0 ? val.join(',') : null
            context.emit('update:modelValue', tmp)
          } else {
            context.emit('update:modelValue', val)
          }
        },
      })
      const change = function (val) {
        if (props.isMultiple) {
          const tmp = val.length >= 0 ? val.join(',') : null
          context.emit('change', tmp)
        } else {
          context.emit('change', val)
        }
      }
      let placeholder =
        '请选择' + props.label
          ? props.label.replace('：', '').replace(':', '')
          : ''

      const rule = computed(() => {
        return [{ required: props.quick, message: '不能为空' }]
      })
      return {
        title,
        placeholder,
        change,
        rule,
      }
    },
  }
</script>
<style lang="scss">
  .xmf-select {
    .el-form-item__content {
      display: flex;
    }

    .el-select {
      width: 100%;
    }
  }
</style>
